package store

import (
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type (
	EnvStore struct {
		db *gorm.DB
	}

	EnvironmentEntity struct {
		RemoteIp     string `gorm:"column:remote_ip;type:text;primaryKey;"`
		Prefix       string `gorm:"column:prefix;type:text;"`
		ForceReplace int    `gorm:"column:force_replace;"`
		Variables    string `gorm:"column:variables;"`
	}
)

func (entity EnvironmentEntity) TableName() string {
	return "tbl_env_info"
}

func (store *EnvStore) SaveOrUpdate(entity EnvironmentEntity) {
	store.db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "remote_ip"}},
		DoUpdates: clause.Assignments(map[string]interface{}{"prefix": entity.Prefix, "force_replace": entity.ForceReplace, "variables": entity.Variables}),
	}).Create(&entity)
}

func (store *EnvStore) FindById(remoteIp string) EnvironmentEntity {
	var entity EnvironmentEntity
	var count int64
	store.db.Where("remote_ip = ?", remoteIp).First(&entity).Count(&count)
	if count == 0 {
		return EnvironmentEntity{}
	}
	return entity
}
